/*
 * @Author: byron
 * @Date: 2021-09-25 22:11:00
 * @LastEditTime: 2022-02-18 20:11:35
 */
import axios from 'axios'
import {
    message,
    Modal
} from 'ant-design-vue'
// import { confirm } from '@/base/confirm'
import store from '@/store'


let loading
let loadingCount = 0

// 不带全局loading的请求实例
export const requestWithoutLoading = createBaseInstance()

// 传入函数是因为需要在处理请求结果handleResponse之前处理loading
// 所以要在内部插入loading拦截器的处理逻辑
export const request = createBaseInstance()
mixinLoading(request.interceptors)
// 通用的axios实例
function createBaseInstance() {
    const instance = axios.create({
        baseURL: process.env.VUE_APP_API_BASE_URL,
        timeout: 10000,
        headers: {
            'Content-Type': ' application/json',
        },
    })
    instance.interceptors.request.use(
        function (config) {
            // 在发送请求之前做些什么
            const token = sessionStorage.getItem('USER_TOKEN')
            if (token) {
                config.headers['Authorization'] = token
            }
            return config
        },
        function (error) {
            // 对请求错误做些什么
            return Promise.reject(error)
        }
    )
    instance.interceptors.response.use(handleResponse, handleError)
    return instance
}

const countDown = (message) => {
    let secondsToGo = 3
    const modal = Modal.warning({
        title: '请求出错啦',
        content: message,
    })
    const interval = setInterval(() => {
        secondsToGo -= 1
    }, 1000)
    setTimeout(() => {
        clearInterval(interval)
        modal.destroy()
    }, secondsToGo * 1000)
}
// 请求错误函数
function handleError(e) {
    console.log('我请求失败了', e);
    countDown(e.message)
}

let expire = 0
// 请求成功函数
function handleResponse(response) {
    if (response.data.code == 401) {
        message.error(response.data.msg)
    } else if (response.data.code == 500) {
        expire++
        if (expire == 1) {
            message.error(response.data.msg)
            store.dispatch('user/logout', false)
        }

    }
    return response
}

// 带全局loading的请求实例

// const SET_AXIOS_LOADING = 'global/setAxiosLoading'
function mixinLoading(interceptors) {
    interceptors.request.use(loadingRequestInterceptor)
    interceptors.response.use(
        loadingResponseInterceptor,
        loadingResponseErrorInterceptor
    )

    // 加载loading实例
    function loadingRequestInterceptor(config) {
        if (!loading) {
            // loading = Loading.service({
            //     target: 'body',
            //     background: 'transparent',
            //     text: '载入中',
            // })
            // store.commit(SET_AXIOS_LOADING, true)
        }
        loadingCount++
        return config
    }

    // 一级响应拦截器
    function handleResponseLoading() {
        loadingCount--
        // 当当前页面全部请求完毕之后关闭loading的加载
        if (loadingCount === 0) {
            // loading.close()
            loading = null
            // store.commit(SET_AXIOS_LOADING, false)
        }
    }

    function loadingResponseInterceptor(response) {
        handleResponseLoading()
        return response
    }

    function loadingResponseErrorInterceptor(e) {
        handleResponseLoading()
        throw e
    }
}